<?php

namespace App\Service\playlet;
use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\PlayletEpisodes;
use App\Model\PlayletEpisodesReplace;
use App\Service\CommicService;
use App\Model\PlayletTag;
use App\Model\Playlet;
use App\Service\queue\DramaService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;
class PlayletExamineService extends CommicService
{
    const cacheDuration = 60 * 15;

    #[Inject]
    private DramaService $dramaService;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }
    const STATUS_ENABLE  = 1;

    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $status      = $params['status'] ?? '';
        $drama_status      = $params['drama_status'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;

        $query = Playlet::query()->select(['id','name','cover','introduction','drama_status','scope_list','album_msg',
            'is_finish','thumbnail','amount','last_episode_number','last_episode_name','pay_start_cid','pay_type','status','likes_number','share_number','album_status','hot_number','created_at','updated_at']);
        $query->where('playlet_type',1);
        if ($keyword) {
            $query->orWhere([['name', 'like', '%'.$keyword.'%']]);
        }
        if ($status != '') {
            $query->where(['status' => $status]);
        }
        if ($drama_status != '') {
            $query->where(['drama_status' => $drama_status]);
        }
        $models = $query->orderBy('id','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            $data['status_name']  = self::$commonStatus[$item->status];
            $playletEpisodesCount = PlayletEpisodes::query()->where(['playlet_id' => $item->id])->count();
            $data['playet_episodes_count'] = $playletEpisodesCount;
            $data['is_finish_name'] = Playlet::$finishStatus[$item->is_finish];
            $data['pay_type_name'] = Playlet::$payType[$item->pay_type];
            $data['drama_status_name'] = self::$dramaStatus[$item->drama_status];
            $data['album_status_name'] = self::$albumStatus[$item->album_status];
            $selectData[] =$data;

        }
        $data = $models->toArray();
        $data['data'] = $selectData;
        return $data;
    }

    public function episodesIndex($id,$type,Array $params){

        $keyword     = $params['keyword'] ?? '';
        $playlet_number     = $params['name'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;
        $uploadStatus = [];

        if($type == 1){
            $query = PlayletEpisodes::query()
                ->select(['id','playlet_id','playlet_number','amount','media_status','media_status_error','is_upload','playlet_number_name','cover','likes_number','share_number','original_play_url','play_url','created_at','updated_at']);
            $uploadStatus = PlayletEpisodes::$uploadwxStatus;
        }else{
            $query = PlayletEpisodes::query()
                ->select(['id','playlet_id','playlet_number','amount',Db::raw('dy_media_status as media_status'),Db::raw('dy_media_status_error as media_status_error'),Db::raw('is_dy_upload as is_upload'),'playlet_number_name','cover','likes_number','share_number','original_play_url','play_url','created_at','updated_at']);
            $uploadStatus = PlayletEpisodes::$uploaddyStatus;
        }


        $query->where('playlet_id' ,$id);

        if ($playlet_number) {
            //查询集数
            $query->where(['playlet_number' => $playlet_number]);
        }

        $models = $query->orderBy('id','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            if(!empty($item->playlet)){
                $data['playlet_name']  = $item->playlet->name;
            }else{
                $data['playlet_name']  = '';
            }
            $data['is_upload_name'] = $uploadStatus[$item->is_upload];
            $data['media_status_name'] = self::$dramaStatus[$item->media_status];
            $selectData[] =$data;
        }
        $data = $models->toArray();
        $data['data'] = $selectData;

        return $data;
    }

    public function auditDrama(int $id,int $type = 1){

        //获取短剧ID
        $playletData = Playlet::query()->where(['id' => $id])->first();
        if(empty($playletData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
        }else{

            if(empty($playletData->producer)){
                return $this->response(SystemCode::SYSTEM_ERROR, '制作方不能为空');
            }
            if(empty($playletData->registration_number)){
                return $this->response(SystemCode::SYSTEM_ERROR, '剧目备案号不能为空');
            }
            if(empty($playletData->registration_number_url)){
                return $this->response(SystemCode::SYSTEM_ERROR, '剧目播放授权材料不能为空');
            }

        }
        //获取这个短剧绑定的第一个小程序，通过此小程序上传短剧
        $appletIds = AppletPlayletRel::query()->where(['playlet_id' => $id])->pluck('applet_id');
        if(empty($appletIds)){
            return $this->response(SystemCode::SYSTEM_ERROR, '短剧没有绑定小程序');
        }

        $appletData = Applet::query()->whereIn('id',$appletIds)->where(['type' => $type])->orderBy('id')->get();
        if(empty($appletData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '小程序不存在');
        }

        //获取小程序下的剧集
        $playletEpisodesData = PlayletEpisodes::query()->where(['playlet_id' => $id])->get();
        if(empty($playletEpisodesData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '该短剧没有剧集');
        }
        //查看这部剧下的是否有未上传媒资
        $errorMsg = [];
        foreach ($playletEpisodesData as $playletEpisodesDatum){

            //微信
            if($type == 1){
                if(empty($playletEpisodesDatum->media_id) || $playletEpisodesDatum->is_upload == 2){

                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.'没有上传到微信资质';
                }

                if($playletEpisodesDatum->is_upload == 4){

                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.' 需要重新上传到微信资质中，请重新上传';
                }
                //抖音
            }else{
                if(empty($playletEpisodesDatum->dy_cloud_id) || $playletEpisodesDatum->is_dy_upload == 2){

                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.'没有上传到抖音资质';
                }

                if($playletEpisodesDatum->is_dy_upload == 4){

                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.' 需要重新上传到抖音资质中，请重新上传';
                }
            }

        }

        if(!empty($errorMsg)){
            return $this->response(SystemCode::SYSTEM_ERROR_DRAMA,'审核失败',$errorMsg);
        }

        $this->dramaService->auditdrama($playletData->id,$appletData[0]->id,$type);

        return $this->response(SystemCode::SYSTEM_SUCCESS);
    }


    public function replaceOnlineDrama(int $id,int $type = 1){

        //获取短剧ID
        $playletData = Playlet::query()->where(['id' => $id])->first();
        if(empty($playletData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
        }else{

            if(empty($playletData->producer)){
                return $this->response(SystemCode::SYSTEM_ERROR, '制作方不能为空');
            }
            if(empty($playletData->registration_number)){
                return $this->response(SystemCode::SYSTEM_ERROR, '剧目备案号不能为空');
            }
            if(empty($playletData->registration_number_url)){
                return $this->response(SystemCode::SYSTEM_ERROR, '剧目播放授权材料不能为空');
            }
        }
        //获取这个短剧绑定的第一个小程序，通过此小程序上传短剧
        $appletIds = AppletPlayletRel::query()->where(['playlet_id' => $id])->pluck('applet_id');
        if(empty($appletIds)){
            return $this->response(SystemCode::SYSTEM_ERROR, '短剧没有绑定小程序');
        }
        $appletData = Applet::query()->whereIn('id',$appletIds)->where(['type' => $type])->orderBy('id')->get();
        if(empty($appletData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '小程序不存在');
        }
        //获取小程序下的剧集
        $replace_episodes_id = PlayletEpisodesReplace::query()->where(['status' => 1,'playlet_id' => $id,'type' => $type])->orderBy('id','desc')->pluck('playlet_episodes_ids')->toArray();
        if(empty($replace_episodes_id)){
            return $this->response(SystemCode::SYSTEM_ERROR, '该短剧没有需要替换的集数');
        }
        $playletEpisodesData = PlayletEpisodes::query()->where(['playlet_id' => $id])->whereIn('id',$replace_episodes_id)->get();
        if(empty($playletEpisodesData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '该短剧没有需要替换剧集');
        }
        //查看这部剧下的是否有未上传媒资
        $errorMsg = [];
        foreach ($playletEpisodesData as $playletEpisodesDatum){
            //微信
            if($type == 1){
                if(empty($playletEpisodesDatum->media_id) || $playletEpisodesDatum->is_upload == 2){

                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.'没有上传到微信资质';
                }

                if($playletEpisodesDatum->is_upload == 4){

                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.' 需要重新上传到微信资质中，请重新上传';
                }
                //抖音
            }else{
                if(empty($playletEpisodesDatum->dy_cloud_id) || $playletEpisodesDatum->is_dy_upload == 2){
                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.'没有上传到抖音资质';
                }
                if($playletEpisodesDatum->is_dy_upload == 4){
                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.' 需要重新上传到抖音资质中，请重新上传';
                }
            }
        }
        if(!empty($errorMsg)){
            return $this->response(SystemCode::SYSTEM_ERROR_DRAMA,'审核失败',$errorMsg);
        }


        PlayletEpisodesReplace::query()->where(['status' => 1,'playlet_id' => $id,'type' => $type])
            ->whereIn('playlet_episodes_ids',$replace_episodes_id)
            ->update(['status' => 2]);

        $this->dramaService->replaceOnlineDrama($playletData->id,$type,$replace_episodes_id);

        return $this->response(SystemCode::SYSTEM_SUCCESS);
    }
}